package com.tan.controller;


import com.tan.entity.Result;
import com.tan.utils.QiNiuUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Api(tags = "文件上传")
@CrossOrigin
public class UploadController extends BaseController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestPart MultipartFile file) throws IOException {
        // 1. 获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 2. 重新设置文件的名称
        String uuid = UUID.randomUUID().toString();
        // 文件的名称 = uuid + 源文件的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName1 = uuid + substring;
        String fileName = fileName1.replaceAll("-", "");
        // 3. 调用图片上传的工具类
        QiNiuUploadUtils.uploadFile(file.getBytes(), fileName);
        Result result = toDataResult(fileName);
        // 4. 响应数据
        return result;
    }
    @ApiOperation("删除图片")
    @GetMapping("/delete")
    public Result delete(String fileName){
        QiNiuUploadUtils.deleteFile(fileName);
        return success();
    }
}
